{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 准备工作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "# set to your own subscription key value\n",
    "subscription_key = \"63b42c4f9d384ee998f93516929843cb\"\n",
    "assert subscription_key\n",
    "\n",
    "# replace <My Endpoint String> with the string from your endpoint URL\n",
    "face_api_url = 'https://api-zjl.cognitiveservices.azure.com/face/v1.0/detect'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 请求"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 请求正文body\n",
    "image_url = 'https://wx1.sinaimg.cn/mw690/008cehsfly1gk41tmwvkhj30gn0m8406.jpg'\n",
    "\n",
    "headers = {'Ocp-Apim-Subscription-Key': subscription_key}\n",
    "\n",
    "# 请求参数parameters\n",
    "params = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'false',\n",
    "    # 可选参数,请仔细阅读API文档\n",
    "    'returnFaceAttributes': 'age,gender,smile,glasses,hair',\n",
    "}\n",
    "\n",
    "response = requests.post(face_api_url, params=params,\n",
    "                         headers=headers, json={\"url\": image_url})\n",
    "# json.dumps 将json--->bytes\n",
    "#json.dumps(response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 查看得出的数据信息\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': '9cf14b9e-c016-4225-8a56-302e6e17f795',\n",
       "  'faceRectangle': {'top': 165, 'left': 124, 'width': 80, 'height': 80},\n",
       "  'faceAttributes': {'smile': 0.118,\n",
       "   'gender': 'male',\n",
       "   'age': 11.0,\n",
       "   'glasses': 'NoGlasses',\n",
       "   'hair': {'bald': 0.03,\n",
       "    'invisible': False,\n",
       "    'hairColor': [{'color': 'red', 'confidence': 1.0},\n",
       "     {'color': 'brown', 'confidence': 0.86},\n",
       "     {'color': 'blond', 'confidence': 0.8},\n",
       "     {'color': 'other', 'confidence': 0.65},\n",
       "     {'color': 'gray', 'confidence': 0.02},\n",
       "     {'color': 'black', 'confidence': 0.0},\n",
       "     {'color': 'white', 'confidence': 0.0}]}}},\n",
       " {'faceId': 'ff1b568c-48ee-4e90-bedb-13f1ade7c2cc',\n",
       "  'faceRectangle': {'top': 129, 'left': 242, 'width': 76, 'height': 76},\n",
       "  'faceAttributes': {'smile': 0.0,\n",
       "   'gender': 'male',\n",
       "   'age': 23.0,\n",
       "   'glasses': 'ReadingGlasses',\n",
       "   'hair': {'bald': 0.01,\n",
       "    'invisible': False,\n",
       "    'hairColor': [{'color': 'brown', 'confidence': 1.0},\n",
       "     {'color': 'red', 'confidence': 0.38},\n",
       "     {'color': 'black', 'confidence': 0.3},\n",
       "     {'color': 'blond', 'confidence': 0.26},\n",
       "     {'color': 'gray', 'confidence': 0.08},\n",
       "     {'color': 'other', 'confidence': 0.01},\n",
       "     {'color': 'white', 'confidence': 0.0}]}}},\n",
       " {'faceId': '030a2d78-d270-4698-8efd-eb71a2497dd5',\n",
       "  'faceRectangle': {'top': 216, 'left': 399, 'width': 71, 'height': 71},\n",
       "  'faceAttributes': {'smile': 0.017,\n",
       "   'gender': 'female',\n",
       "   'age': 12.0,\n",
       "   'glasses': 'NoGlasses',\n",
       "   'hair': {'bald': 0.01,\n",
       "    'invisible': False,\n",
       "    'hairColor': [{'color': 'brown', 'confidence': 1.0},\n",
       "     {'color': 'blond', 'confidence': 0.83},\n",
       "     {'color': 'red', 'confidence': 0.39},\n",
       "     {'color': 'gray', 'confidence': 0.15},\n",
       "     {'color': 'black', 'confidence': 0.09},\n",
       "     {'color': 'other', 'confidence': 0.02},\n",
       "     {'color': 'white', 'confidence': 0.0}]}}}]"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results = response.json()\n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 字典提取"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.0版本\n",
    "#### 思路： 提取到原数据中需要的键值后，再赋值，然后再存成字典。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "glasses_1 = results[0]['faceAttributes']['glasses']\n",
    "smile_1 = results[0]['faceAttributes']['smile']\n",
    "hairColor_1 =  results[0]['faceAttributes']['hair']['hairColor']\n",
    "age_1 = results[0]['faceAttributes']['age']\n",
    "gender_1 = results[0]['faceAttributes']['gender']\n",
    "\n",
    "dict_1 = {'name':'Ron','glasses':glasses_1,'smile':smile_1,'hairColor':hairColor_1,'age':age_1,'gender':gender_1}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "glasses_2 = results[1]['faceAttributes']['glasses']\n",
    "smile_2 = results[1]['faceAttributes']['smile']\n",
    "hairColor_2 =  results[1]['faceAttributes']['hair']['hairColor']\n",
    "age_2 = results[1]['faceAttributes']['age']\n",
    "gender_2 = results[1]['faceAttributes']['gender']\n",
    "\n",
    "dict_2 = {'name':'Harry','glasses':glasses_2,'smile':smile_2,'hairColor':hairColor_2,'age':age_2,'gender':gender_2}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "glasses_3 = results[2]['faceAttributes']['glasses']\n",
    "smile_3 = results[2]['faceAttributes']['smile']\n",
    "hairColor_3 =  results[2]['faceAttributes']['hair']['hairColor']\n",
    "age_3 = results[2]['faceAttributes']['age']\n",
    "gender_3 = results[2]['faceAttributes']['gender']\n",
    "\n",
    "dict_3 = {'name':'Hermione','glasses':glasses_3,'smile':smile_3,'hairColor':hairColor_3,'age':age_3,'gender':gender_3}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Ron', 'glasses': 'NoGlasses', 'smile': 0.118, 'hairColor': [{'color': 'red', 'confidence': 1.0}, {'color': 'brown', 'confidence': 0.86}, {'color': 'blond', 'confidence': 0.8}, {'color': 'other', 'confidence': 0.65}, {'color': 'gray', 'confidence': 0.02}, {'color': 'black', 'confidence': 0.0}, {'color': 'white', 'confidence': 0.0}], 'age': 11.0, 'gender': 'male'}\n",
      "**********************\n",
      "{'name': 'Harry', 'glasses': 'ReadingGlasses', 'smile': 0.0, 'hairColor': [{'color': 'brown', 'confidence': 1.0}, {'color': 'red', 'confidence': 0.38}, {'color': 'black', 'confidence': 0.3}, {'color': 'blond', 'confidence': 0.26}, {'color': 'gray', 'confidence': 0.08}, {'color': 'other', 'confidence': 0.01}, {'color': 'white', 'confidence': 0.0}], 'age': 23.0, 'gender': 'male'}\n",
      "**********************\n",
      "{'name': 'Hermione', 'glasses': 'NoGlasses', 'smile': 0.017, 'hairColor': [{'color': 'brown', 'confidence': 1.0}, {'color': 'blond', 'confidence': 0.83}, {'color': 'red', 'confidence': 0.39}, {'color': 'gray', 'confidence': 0.15}, {'color': 'black', 'confidence': 0.09}, {'color': 'other', 'confidence': 0.02}, {'color': 'white', 'confidence': 0.0}], 'age': 12.0, 'gender': 'female'}\n",
      "**********************\n"
     ]
    }
   ],
   "source": [
    "print(dict_1)\n",
    "print('**********************')\n",
    "print(dict_2)\n",
    "print('**********************')\n",
    "print(dict_3)\n",
    "print('**********************')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 缺陷：1. 类似代码重复三遍，不够简洁  2.直接打印字典，不够美观"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.0版本\n",
    "### 思路：使用遍历和嵌套"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name:Ron\n",
      "glasses:NoGlasses\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "can only concatenate str (not \"float\") to str",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-46-aa67a30f036a>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;31m# 由于键值存在数字和字母都存在，甚至混合的情况，所以不能用'+'连接，会报错！应该用'，'连接！\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mk\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mv\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mdict_1\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;34m':'\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0mv\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: can only concatenate str (not \"float\") to str"
     ]
    }
   ],
   "source": [
    "# 踩坑：\n",
    "# 由于键值存在数字和字母都存在，甚至混合的情况，所以不能用'+'连接，会报错！应该用'，'连接！\n",
    "for k,v in dict_1.items():\n",
    "    print(k+':'+v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name : Ron\n",
      "glasses : NoGlasses\n",
      "smile : 0.118\n",
      "hairColor : [{'color': 'red', 'confidence': 1.0}, {'color': 'brown', 'confidence': 0.86}, {'color': 'blond', 'confidence': 0.8}, {'color': 'other', 'confidence': 0.65}, {'color': 'gray', 'confidence': 0.02}, {'color': 'black', 'confidence': 0.0}, {'color': 'white', 'confidence': 0.0}]\n",
      "age : 11.0\n",
      "gender : male\n"
     ]
    }
   ],
   "source": [
    "for k,v in dict_1.items():\n",
    "    print(k,':',v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name : Ron\n",
      "glasses : NoGlasses\n",
      "smile : 0.118\n",
      "hairColor : [{'color': 'red', 'confidence': 1.0}, {'color': 'brown', 'confidence': 0.86}, {'color': 'blond', 'confidence': 0.8}, {'color': 'other', 'confidence': 0.65}, {'color': 'gray', 'confidence': 0.02}, {'color': 'black', 'confidence': 0.0}, {'color': 'white', 'confidence': 0.0}]\n",
      "age : 11.0\n",
      "gender : male\n",
      "----------------------------------------------------------------------------------------------\n",
      "name : Harry\n",
      "glasses : ReadingGlasses\n",
      "smile : 0.0\n",
      "hairColor : [{'color': 'brown', 'confidence': 1.0}, {'color': 'red', 'confidence': 0.38}, {'color': 'black', 'confidence': 0.3}, {'color': 'blond', 'confidence': 0.26}, {'color': 'gray', 'confidence': 0.08}, {'color': 'other', 'confidence': 0.01}, {'color': 'white', 'confidence': 0.0}]\n",
      "age : 23.0\n",
      "gender : male\n",
      "----------------------------------------------------------------------------------------------\n",
      "name : Hermione\n",
      "glasses : NoGlasses\n",
      "smile : 0.017\n",
      "hairColor : [{'color': 'brown', 'confidence': 1.0}, {'color': 'blond', 'confidence': 0.83}, {'color': 'red', 'confidence': 0.39}, {'color': 'gray', 'confidence': 0.15}, {'color': 'black', 'confidence': 0.09}, {'color': 'other', 'confidence': 0.02}, {'color': 'white', 'confidence': 0.0}]\n",
      "age : 12.0\n",
      "gender : female\n",
      "----------------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "dict = [dict_1,dict_2,dict_3]\n",
    "for i in dict: # 踩坑：这里不能用if ，要用for\n",
    "    for k,v in i.items():\n",
    "        print(k,':',v)\n",
    "    print(\"----------------------------------------------------------------------------------------------\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数的方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 还……不太会"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_msg(num,item,item_=None):\n",
    "    \"\"\"\"\"\"\n",
    "    msg = results[num]['faceAttributes']['item']['item_']\n",
    "    return  msg\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'glasses' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-52-502a7294d47c>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mget_msg\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mglasses\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m: name 'glasses' is not defined"
     ]
    }
   ],
   "source": [
    "get_msg(1,glasses)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
